#include <signal.h>
#include "test.h"
#include "Log.h"
#include <boost/function.hpp>
#include <boost/bind.hpp>

#define LEN 16384
using namespace sevent;

EchoServer::EchoServer(const std::string name, const std::string ip, const int port)
:_server(name, ip, port){
	_server.setTaskFunc(boost::bind(&EchoServer::taskExecute, this, _1));
}

int EchoServer::taskExecute(Connect *c, Message *msg){
	LOG_DEBUG_VA("Task start execute");
	string s = msg->toString();
	LOG_DEBUG_VA("get Message %s by length: %d", s.c_str(), s.length());
	//do something
	int len= c->send(msg);
	LOG_DEBUG_VA("send Message over length: %d", len);
	return 0;
}

int main(int argc, char **argv){
	
	//if (!init_logger("./logs/", "TRACE")) {
	if (!init_logger("./logs/", "OFF")) {
		cout << "logger init failed" << endl;
		return -1;
	}
	signal(SIGPIPE,SIG_IGN);
	//Server *s = new Server("test", "199.155.122.11", 3330);
	//Server *s = new Server("test", "127.0.0.1", 3330);
	EchoServer *s = new EchoServer("test1", "0.0.0.0", 3330);
	s->start(1); 
	s->wait(); 
	return 0;
}


/*
int taskExecute1(Connect *c){
	LOG_DEBUG_VA("Task start execute");
	char *buf = new char[LEN];
	int len = 0;
	len = c->read(buf, LEN, 10000);
	//len = ::read(c->fd(), buf, LEN);
	if(len == 0){
		LOG_DEBUG_VA("Task read 0 bytes, going to close this Connect");
		c->close();
		return 0;
	}
	LOG_DEBUG_VA("Task read %d bytes from %x:%d", len, c, c->fd());
	//do something
	
	int sockfd;
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd == -1){
		perror("socket()");
		return -1;
	}
	
	struct sockaddr_in dest_addr;
	bzero(&dest_addr, sizeof(dest_addr));
	dest_addr.sin_family = AF_INET;
	dest_addr.sin_port = htons(3331);
	dest_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	
	int flag = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int));
	if (connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in)) != 0){
		perror("connect()");
		close(sockfd);
		return -1;
	}
	len = ::write(sockfd, buf, LEN);
	len = ::read(sockfd, buf, LEN);
	close(sockfd);
	
	len = c->write(buf, LEN, 10000);
	//len = ::write(c->fd(), buf, LEN);
	delete [] buf;
	LOG_DEBUG_VA("Task write %d bytes", len);
	return 0;
}

int taskExecute2(Connect *c){
	LOG_DEBUG_VA("Task start execute");
	char *buf = new char[LEN];
	int len = 0;
	len = c->read(buf, LEN, 10000);
	//len = ::read(c->fd(), buf, LEN);
	if(len == 0){
		LOG_DEBUG_VA("Task read 0 bytes, going to close this Connect");
		c->close();
		return 0;
	}
	LOG_DEBUG_VA("Task read %d bytes from %x:%d", len, c, c->fd());
	//do something
	
	len = c->write(buf, LEN, 10000);
	//len = ::write(c->fd(), buf, LEN);
	delete [] buf;
	LOG_DEBUG_VA("Task write %d bytes", len);
	return 0;
}
*/

